import {
    Loading,
    Message
} from 'element-ui'
import qs from 'qs'
import {
    removeKey
} from './tool'
import router from '@/router'
import axios from 'axios'

let baseUrl = ''
if (process.env.NODE_ENV === 'development') {
    baseUrl = ''
} else if (process.env.NODE_ENV === 'production') {
    baseUrl = 'http://api.16690.meidie.cn'
}

// 超时时间
axios.defaults.timeout = 10000

/*请求合并只出现一次loading*/
let needLoadingRequestCount = 0
let loadinginstace

function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        loading('start') /*loading加载*/
    }
    needLoadingRequestCount++
}

function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        setTimeout(tryCloseLoading, 300) /*300ms 间隔内的 loading 合并为一次*/
    }
}
const tryCloseLoading = () => {
    if (needLoadingRequestCount === 0) {
        loading('end') /*loading加载*/
    }
}

/*loading加载*/
function loading(str) {
    if (str == 'start') {
        loadinginstace = Loading.service({
            fullscreen: true
        })
    } else if (str == 'end') {
        loadinginstace.close()
    }
}

// http请求拦截器
axios.interceptors.request.use(
    config => {
        const token = window.localStorage.getItem('token')
        if (token) {
            //添加认证头部信息
            config.headers.common['token'] = token
        }
        if (config.showLoading) {
            showFullScreenLoading()
        }
        return config
    },
    error => {
        /*Message.error({
        message: '加载超时'
    });*/
        return Promise.reject(error)
    }
)

axios.interceptors.response.use(
    response => {
        // 响应成功关闭loading
        if (response.config.showLoading) {
            tryHideFullScreenLoading()
        }
        let data = response.data
        if (data.code == -10000) {
            removeKey('token')
            router.push('/login')
            /*Message.error({
            message: 'token过期了，请重新登录'
        });*/
        } else if (data.code != 1) {
            Message.error({
                message: data.message
            })
        }
        return response
    },
    error => {
        /*Message.error({
        message: '加载超时'
    });*/
        if (error.config.showLoading) {
            tryHideFullScreenLoading() // 消除loading
        }
        return Promise.resolve(error.response)
    }
)

const checkStatus = response => {
    // loading
    // 如果http状态码正常，则直接返回数据
    if (response && response.status === 200) {
        return response.data
    } else {
        return {
            code: 500,
            message: '接口挂了'
        }
    }
}

function checkCode(res) {
    // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
    if (res.status === -404) {
        // console.log(res.msg)
    }
    if (res.data && !res.data.success) {
        // console.log(res)
        // console.log(res.data.msg)
    }
    return res
}

export default {
    post(url, data, config = {
        showLoading: true
    }) {
        return axios({
            method: 'post',
            baseURL: baseUrl + url,
            data: qs.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
            .then(response => {
                return checkStatus(response)
            })
            .then(res => {
                return checkCode(res)
            })
    },
    get(url, params, config = {
        showLoading: true
    }) {
        return axios({
            method: 'get',
            baseURL: baseUrl + url,
            params, // get 请求时带的参数
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
            .then(response => {
                return checkStatus(response)
            })
            .then(res => {
                return checkCode(res)
            })
    }
}
